<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\pt\controller;

use think\admin\Controller;
use think\facade\Db;

/**
 * Class Index
 * @package app\group\controller
 */
class Index extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'PtGroupAct';

    /**
     * 拼团活动列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '拼团活动列表';
        $this->_query($this->table)->dateBetween('add_time')->order('update_time desc')->page();
    }

    /**
     * 拼团失败
     */
    public function groupFail()
    {
        $group_id = $this->request->get('id', '', 'int');
        if (empty($group_id)) $this->error('缺少必要参数');
        $top_list = Db::table('pt_top_order')->alias('a')
            ->field('a.*,b.num')
            ->join('pt_son_order b', 'a.top_id=b.top_id')
            ->where([['a.group_id', '=', $group_id], ['a.pay_status', '=', 1]])->select()->toArray();
        $now_time = date('Y-m-d H:i:s');
        foreach ($top_list as $value) {
            Db::startTrans();
            try {
                #添加退款申请
                $return_id = Db::table('pt_refund')->insertGetId([
                    'refund_no' => getOrderSn('tui'),
                    'top_id' => $value['top_id'],
                    'user_id' => $value['user_id'],
                    'refund_num' => $value['num'],
                    'refund_money' => $value['real_pay'],
                    'refund_score' => $value['score'],
                    'refund_order_status' => 1,
                    'type_index' => 1,
                    'reason_index' => 4,
                    'reason' => '拼团失败，系统自动退款',
                    'add_time' => $now_time,
                    'update_time' => $now_time
                ]);
                if (!$return_id) throw new \Exception('top_id:' . $value['top_id'] . ',退款申请添加失败');
                #退款处理
                $return_info = OrderService::instance()->doConfirmReturn($return_id, $value['real_pay'], 2);
                if ($return_info['code'] == -1) throw new \Exception($return_info['info']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                addException(4, '拼团失败，自动退款失败', $e->getMessage());
            }
        }
    }

    /**
     * 拼团添加
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function groupAdd()
    {
        $this->_applyFormToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 表单数据处理
     * @param $vo
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            #科目列表
            $menu_list = Db::table('pt_menu')->where(['status' => 1])->select()->toArray();
            $new_menu_list = $this->arr2tree($menu_list);
            $vo['menu_list'] = $new_menu_list;
            if (empty($vo['price_list'])) $vo['price_list'] = json_encode([]);
            $vo['menu_keys'] = !empty($vo['menu_keys']) ? explode(',', $vo['menu_keys']) : [];
        } elseif ($this->request->isPost()) {
            $vo['menu_keys'] = implode(',', $vo['menu_keys']);
        }
    }

    /**
     * 一维数组生成数据树
     * @param array $list 待处理数据
     * @param string $cid 自己的主键
     * @param string $pid 上级的主键
     * @param string $sub 子数组名称
     * @return array
     */
    public static function arr2tree(array $list, string $cid = 'id', string $pid = 'pid', string $sub = 'sub'): array
    {
        [$tree, $tmp] = [[], array_combine(array_column($list, $cid), array_values($list))];
        foreach ($list as $vo) isset($vo[$pid]) && isset($tmp[$vo[$pid]]) ? $tmp[$vo[$pid]][$sub][] = &$tmp[$vo[$cid]] : $tree[] = &$tmp[$vo[$cid]];
        unset($tmp, $list);
        return $tree;
    }

    /**
     * 用户拉入黑名单
     * @auth true
     */
    public function black_add()
    {
        $this->_applyFormToken();
        $id_list = $this->request->post('id');
        $bool = $this->_query($this->table)->whereIn('id', $id_list)->update(['is_forbid' => '1']);
        if ($bool) {
            $this->success('禁用成功！');
        } else {
            $this->error("禁用失败，请稍候再试！");
        }
    }

    /**
     * 用户移出黑名单
     * @auth true
     */
    public function black_del()
    {
        $this->_applyFormToken();
        $id_list = $this->request->post('id');
        $bool = $this->_query($this->table)->whereIn('id', $id_list)->update(['is_forbid' => '0']);
        if ($bool) {
            $this->success('启用成功！');
        } else {
            $this->error("启用失败，请稍候再试！");
        }
    }


    /**
     * 属性添加
     * @auth true
     * attr_status 1:已添加 2：待添加 3：待删除
     */
    public function attrAdd()
    {
        $this->_applyFormToken();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            //var_dump($data);exit;
            if (empty($data['group_id']) || empty($data['attr_data'])) $this->error('缺少必要参数');
            $now_time = date('Y-m-d H:i:s');
            foreach ($data['attr_data'] as $value) {
                if ($value['attr_status'] == 1) {
                    $value['update_time'] = $now_time;
                    unset($value['key'], $value['attr_status'], $value['LAY_TABLE_INDEX']);
                    $bool = Db::table('pt_product_attr')->where(['group_id' => $data['group_id'], 'attr_id' => $value['attr_id']])->save($value);
                    if (!$bool) {
                        $this->error('编辑失败');
                        break;
                    }
                } else {
                    $value['add_time'] = $value['update_time'] = $now_time;
                    unset($value['attr_id'], $value['key'], $value['attr_status'], $value['LAY_TABLE_INDEX']);
                    $bool = Db::table('pt_product_attr')->insert($value);
                    if (!$bool) {
                        $this->error('新增失败');
                        break;
                    }
                }
            }
            $this->success('success');
        } else {
            $group_id = $this->request->get('id', '', 'int');
            if (empty($group_id)) $this->error('缺少必要参数');
            $attr_list = Db::table('pt_product_attr')->where(['group_id' => $group_id])->select()->toArray();
            if (!empty($attr_list)) {
                foreach ($attr_list as $key => &$item) {
                    $item['attr_status'] = 1;
                    $item['key'] = $key;
                }
            } else {
                $attr_list = [];
            }
            $this->assign('attr_list', json_encode($attr_list));
            $this->assign('group_id', $group_id);
            $this->fetch();
        }

    }

    /**
     * 属性删除
     */
    public function attrDel()
    {
        $attr_id = $this->request->post('attr_id', '', 'int');
        if (empty($attr_id)) $this->error('缺少必要参数');
        $bool = Db::table('pt_product_attr')->where(['attr_id' => $attr_id])->delete();
        if ($bool) {
            $this->success('success');
        } else {
            $this->error('error');
        }
    }


}